package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 封装输出流
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    // 输出指定内容
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    // 根据指定path，读取绝对路径上的静态资源文件，通过输入流输出
    public void outputHtml(String path) throws IOException {
        String resource = StaticResourceUtil.getAbsolutePath(path);

        File file = new File(resource);
        if(file.exists() && file.isFile()){
            // 读取静态资源，并输出
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 文件不存在，输出404
            output(HttpProtocolUtil.getHttpHead404());
        }
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }
}
